package com.kbtd.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kbtd.dto.Result;
import com.kbtd.entity.SeckillVoucher;
import com.kbtd.entity.VoucherOrder;
import com.kbtd.mapper.VoucherOrderMapper;
import com.kbtd.service.ISeckillVoucherService;
import com.kbtd.service.IVoucherOrderService;
import com.kbtd.service.mq.BlockMQ;
import com.kbtd.utils.UserHolder;
import com.kbtd.utils.redis.RedisIdWorker;
import com.kbtd.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

import static com.kbtd.constant.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisIdWorker redisIdWorker;

    private IVoucherOrderService proxy;
    private static final DefaultRedisScript<Integer> SECKILL_MQ_SCRIPT;
    private static final DefaultRedisScript<Integer> SECKILL_BLOCK_SCRIPT;

    static {
        SECKILL_MQ_SCRIPT = new DefaultRedisScript<>();
        SECKILL_MQ_SCRIPT.setLocation(new ClassPathResource("lua/seckill_mq.lua"));
        SECKILL_MQ_SCRIPT.setResultType(Integer.class);

        SECKILL_BLOCK_SCRIPT = new DefaultRedisScript<>();
        SECKILL_BLOCK_SCRIPT.setLocation(new ClassPathResource("lua/seckill_block.lua"));
        SECKILL_BLOCK_SCRIPT.setResultType(Integer.class);
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        return seckillVoucherV3(voucherId);
    }

    //redis消息队列实现异步下单
    public Result seckillVoucherV3(Long voucherId) {
        //1.1获取用户id
        Long userId = UserHolder.getUser().getId();
        //获取订单id
        String lockKey = RedisUtils.createKey(LOCK_ORDER_KEY_PREFIX, userId.toString());
        Long orderId = redisIdWorker.nextId(lockKey);
        //1.2执行lua脚本
        String stockKey = RedisUtils.createKey(SECKILL_STOCK_KEY_PREFIX, voucherId.toString());
        String orderKey = RedisUtils.createKey(SECKILL_ORDER_KEY_PREFIX, orderId.toString());
        Integer result = stringRedisTemplate.execute(
                SECKILL_MQ_SCRIPT,
                Arrays.asList(stockKey, orderKey),
                voucherId.toString(), userId.toString(), orderId.toString()
        );
        //2.判断执行结果是否为0
        if (result != 0) {
            //2.1不为0，没有购买资格
            return Result.fail(result == 1 ? "库存不足！" : "不可重复下单！");
        }
        //5返回订单id
        return Result.ok(orderId);
    }

    @Deprecated
    public Result seckillVoucherV2(Long voucherId) {
        //1.1获取用户id
        Long userId = UserHolder.getUser().getId();
        //1.2执行lua脚本
        Integer result = stringRedisTemplate.execute(
                SECKILL_MQ_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        //2.判断执行结果是否为0
        if (result != 0) {
            //2.1不为0，没有购买资格
            return Result.fail(result == 1 ? "库存不足" : "不能重复下单");
        }
        //3--4为0，有购买资格，把下单信息保存到阻塞队列中
        //3.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //3.1订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        //3.2保存用户id
        voucherOrder.setUserId(userId);
        //3.3优惠券id
        voucherOrder.setVoucherId(voucherId);
        //4.保存订单信息
        //4.1放入阻塞队列
        BlockMQ.productMsg(BlockMQ.SECKILL_MESSAGE_TYPE, voucherOrder);
        return Result.ok(orderId);
    }

    //异步订单数据保存到数据库
    @Override
    @Transactional
    public boolean createVoucherOrder(VoucherOrder voucherOrder) {
        //1.一人一单判断
        Long userId = voucherOrder.getUserId();
        //1.1查询订单
        Long count = query().eq("user_id", userId)
                .eq("voucher_id", voucherOrder.getVoucherId())
                .count();
        //1.2判断是否存在
        if (count > 0) {
            log.error("用户已经购买过一次");
            throw new RuntimeException("用户已经购买过一次");
        }
        //2.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1") //set stock = stock-1
                .eq("voucher_id", voucherOrder.getVoucherId()) //where voucher_id==voucherId
                .gt("stock", 0) //where stock >0
                .update();
        if (!success) {
            //扣减失败
            log.error("库存不足！");
            throw new RuntimeException("库存不足！");
        }
        save(voucherOrder);
        return true;
    }

    // 同步秒杀下单
    @Deprecated
    public Result seckillVoucherV1(Long voucherId) {
        //1.查询优惠卷
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if (ObjectUtils.isEmpty(voucher)) {
            Result.fail("优惠劵秒杀活动不存在！");
        }
        //2.判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            //尚未开始
            return Result.fail("秒杀尚未开始");
        }
        //3.判断秒杀是否已经结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            //已经结束
            return Result.fail("秒杀已经结束");
        }
        //4.判断库存是否充足
        if (voucher.getStock() < 1) {
            return Result.fail("库存不足");
        }
        //5.查询用户id
        Long userId = UserHolder.getUser().getId();
        //6.对相同用户id的操作加锁，防止并行执行，一人多单
        //6.1创建锁对象
        //使用的redisson获取的锁类
        String lockKey = RedisUtils.createKey(LOCK_ORDER_KEY_PREFIX, userId.toString());
        RLock lock = redissonClient.getLock(lockKey);
        //6.2获取锁
        boolean isLock = lock.tryLock();
        //6.3判断获取锁是否成功
        if (!isLock) {
            //获取锁失败，返回错误
            return Result.fail("用户正在下单，请勿重复操作！");
        }
        try {
            //7获取代理对象（确保事务Transactional生效，保证createVoucherOrder 提交完事务之后再释放锁）
            //原因：事务是由SpringBoot代理对象通过代理模式实现，直接调用会导致事务失效
            VoucherOrderServiceImpl proxy = (VoucherOrderServiceImpl) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId, userId);
        } finally {
            //8.释放锁
            lock.unlock();
        }
    }

    //保存订单数据到数据库
    @Transactional
    public Result createVoucherOrder(Long voucherId, Long userId) {
        //1.一人一单判断
        //1.1查询订单
        Long count = query().eq("user_id", userId)
                .eq("voucher_id", voucherId)
                .count();
        //1.2判断是否存在
        if (count > 0) {
            log.error("商品限购，下单失败！");
            return Result.fail("商品限购，下单失败！");
        }
        //2.扣减库存（乐观锁）
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1") //set stock = stock-1
                .eq("voucher_id", voucherId) //where voucher_id==voucherId
                .gt("stock", 0) //where stock >0
                .update();
        if (!success) {
            //扣减失败
            log.error("库存不足！");
            return Result.fail("库存不足！");
        }
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setId(redisIdWorker.nextId(VOUCHER0_ORDER_ID));
        voucherOrder.setUserId(userId);
        save(voucherOrder);
        return Result.ok();
    }
}